package com.tarena.lbs.basic.service.impl;

import com.tarena.lbs.basic.dao.mapper.AreaMapper;
import com.tarena.lbs.basic.pojo.dto.AreaQuery;
import com.tarena.lbs.basic.pojo.po.AreaPO;
import com.tarena.lbs.basic.pojo.vo.AreaVO;
import com.tarena.lbs.basic.pojo.vo.TagVO;
import com.tarena.lbs.basic.service.AreaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class AreaServiceImpl implements AreaService {
    @Autowired
    AreaMapper areaMapper;


    @Override
    public List<AreaVO> selectByParentId(Long id) {
        log.debug("通过上级地区查询地区业务参数:{}",id);
        AreaQuery areaQuery = new AreaQuery();
        areaQuery.setParentId(id);
        List<AreaPO> areaPOS = areaMapper.select(areaQuery);
        List<AreaVO> areaVOS = new ArrayList<>();
        for(AreaPO areaPO:areaPOS){
            AreaVO areaVO = new AreaVO();
            BeanUtils.copyProperties(areaPO,areaVO);
            areaVOS.add(areaVO);
        }
        return areaVOS;
    }

    @Override
    public List<AreaVO> selectByDepth(Long depth) {
        log.debug("查询各级别地区业务参数:{}",depth);
        AreaQuery areaQuery = new AreaQuery();
        areaQuery.setDepth(depth);
        List<AreaPO> areaPOS = areaMapper.select(areaQuery);
        List<AreaVO> areaVOS = new ArrayList<>();
        for(AreaPO areaPO:areaPOS){
            AreaVO areaVO = new AreaVO();
            BeanUtils.copyProperties(areaPO,areaVO);
            areaVOS.add(areaVO);
        }
        return areaVOS;
    }

    @Override
    public List<AreaVO> selectTree() {
        log.debug("查询地市树业务");

        List<AreaVO> provinces  = selectByDepth(1L);

        List<AreaVO> newCities = new ArrayList<>();
        List<AreaVO> tree = new ArrayList<>();

        for(AreaVO areaVO:provinces){
            List<AreaVO> cities = selectByParentId(areaVO.getId());

            for(AreaVO city:cities){
                List<AreaVO> districts = selectByParentId(city.getId());

                city.setChildren(districts);
                newCities.add(city);
            }

            areaVO.setChildren(newCities);
            tree.add(areaVO);
            newCities = new ArrayList<>();
        }

        return tree;
    }



}
